﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using APNS.NET.Extensions;

namespace APNS.NET
{

    // Represents a notification that can be sent to a device. Contains notification id (user defined), 
    // expiry date for the notification, device token that represents the device to send to and the actual 
    // payload to send to the device
    public class ApnsNotification
    {
        
        private const byte EnhancedNotificationCommand = 1;

        public virtual DateTime Expiry { get; set; }
        public virtual DeviceToken DeviceToken { get; set; }
        public virtual NotificationPayload NotificationPayload { get; set; }       
 
        public ApnsNotification()
        {            
        }

        public ApnsNotification(DeviceToken deviceToken, NotificationPayload notificationPayload)
        {
            this.DeviceToken = deviceToken;
            this.NotificationPayload = notificationPayload;
        }

        // Returns the notification as a byte representation that can be sent directly to the
        // apple APNS service.
        public byte[] ToByteArray(int notificationId)
        {                      
            using(MemoryStream outputStream = new MemoryStream())
            {
                byte[] deviceTokenBytes = DeviceToken.ToByteArray();
                byte[] notificationPayloadBytes = NotificationPayload.ToByteArray();

                outputStream.WriteByte(EnhancedNotificationCommand);
                outputStream.Write(BitConverter.GetBytes(notificationId));
                outputStream.Write(BitConverter.GetBytes(Expiry.ToEpochTime()));

                outputStream.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(Convert.ToInt16(deviceTokenBytes.Length))));
                outputStream.Write(deviceTokenBytes);
                
                outputStream.Write(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(Convert.ToInt16(notificationPayloadBytes.Length))));
                outputStream.Write(notificationPayloadBytes);

                outputStream.Flush();
                return outputStream.GetBuffer();
            }
            
        }

    }
}
